<template>
  <div :class="['breadcrumb-box mask-image', !globalStore.breadcrumbIcon && 'no-icon']">
    <el-breadcrumb :separator-icon="ArrowRight">
      <transition-group name="breadcrumb" tag="div">
        <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="item.path">
          <div
            :class="['el-breadcrumb__inner', isClickable(item, index) ? 'is-link' : 'is-disabled']"
            @click="onBreadcrumbClick(item, index)"
            @contextmenu.prevent="onContextMenu($event, item)"
            :title="isClickable(item, index) ? `路径: ${item.path}` : item.meta.title"
          >
            <el-icon v-show="item.meta.icon && globalStore.breadcrumbIcon" class="breadcrumb-icon">
              <component :is="item.meta.icon"></component>
            </el-icon>
            <span class="breadcrumb-title">{{ item.meta.title }}</span>
          </div>
        </el-breadcrumb-item>
      </transition-group>
    </el-breadcrumb>

    <!-- 右键菜单 -->
    <div
      v-if="contextMenuVisible"
      class="context-menu-wrapper"
      :style="{ left: contextMenuPosition.x + 'px', top: contextMenuPosition.y + 'px' }"
      @click.stop
    >
      <div class="context-menu">
        <div class="menu-item" @click="copyPath">
          <el-icon><DocumentCopy /></el-icon>
          <span>复制路径</span>
        </div>
        <div class="menu-item" @click="copyTitle">
          <el-icon><Document /></el-icon>
          <span>复制名称</span>
        </div>
        <div class="menu-divider"></div>
        <div class="menu-item" @click="refreshPage">
          <el-icon><Refresh /></el-icon>
          <span>刷新页面</span>
        </div>
      </div>
    </div>

    <!-- 点击外部关闭右键菜单 -->
    <div v-if="contextMenuVisible" class="context-menu-overlay" @click="closeContextMenu"></div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from "vue"
import { HOME_URL } from "@/config"
import { useRoute, useRouter } from "vue-router"
import { ArrowRight, DocumentCopy, Document, Refresh } from "@element-plus/icons-vue"
import { useAuthStore } from "@/stores/modules/auth"
import { useGlobalStore } from "@/stores/modules/global"
import { ElMessage } from "element-plus"

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const globalStore = useGlobalStore()

const contextMenuVisible = ref(false)
const contextMenuPosition = ref({ x: 0, y: 0 })
const currentContextItem = ref<Menu.MenuOptions | null>(null)

const breadcrumbList = computed(() => {
  const currentPath = route.matched[route.matched.length - 1].path
  let breadcrumbData = authStore.breadcrumbListGet[currentPath] ?? []
  // 如果是配置组参数路由，则加上实验管理路由在前 作为面包屑
  if (currentPath == "/experimentGroup") {
    const pathList = authStore.breadcrumbListGet["/experimentManage"]
    breadcrumbData = [...pathList, ...breadcrumbData]
  }
  // 🙅‍♀️不需要首页面包屑可删除以下判断
  if (breadcrumbData[0]?.path !== HOME_URL) {
    breadcrumbData = [
      { path: HOME_URL, meta: { icon: "HomeFilled", title: "首页" }, component: "/home/index" },
      ...breadcrumbData
    ]
  }
  return breadcrumbData
})
console.log("breadcrumbList", breadcrumbList.value)

// 判断面包屑项是否可点击
const isClickable = (item: Menu.MenuOptions, index: number) => {
  // 最后一项不可点击
  if (index === breadcrumbList.value.length - 1) return false
  // 没有 component 的菜单项不可点击（通常是有子菜单的父级菜单）
  if (!item.component) return false
  return true
}

// Click Breadcrumb
const onBreadcrumbClick = (item: Menu.MenuOptions, index: number) => {
  if (isClickable(item, index)) {
    router.push(item.path)
  }
}

// 右键菜单
const onContextMenu = (event: MouseEvent, item: Menu.MenuOptions) => {
  event.preventDefault()
  currentContextItem.value = item
  contextMenuPosition.value = { x: event.clientX, y: event.clientY }
  contextMenuVisible.value = true
}

// 关闭右键菜单
const closeContextMenu = () => {
  contextMenuVisible.value = false
  currentContextItem.value = null
}

// 复制路径
const copyPath = async () => {
  if (currentContextItem.value) {
    try {
      await navigator.clipboard.writeText(currentContextItem.value.path)
      ElMessage.success("路径已复制到剪贴板")
    } catch (error) {
      ElMessage.error("复制失败，请手动复制")
    }
  }
  closeContextMenu()
}

// 复制名称
const copyTitle = async () => {
  if (currentContextItem.value) {
    try {
      await navigator.clipboard.writeText(currentContextItem.value.meta.title || "")
      ElMessage.success("名称已复制到剪贴板")
    } catch (error) {
      ElMessage.error("复制失败，请手动复制")
    }
  }
  closeContextMenu()
}

// 刷新页面
const refreshPage = () => {
  window.location.reload()
  closeContextMenu()
}
</script>

<style scoped lang="scss">
.breadcrumb-box {
  display: flex;
  align-items: center;
  overflow: hidden;
  position: relative;

  .el-breadcrumb {
    white-space: nowrap;
    .el-breadcrumb__item {
      position: relative;
      display: inline-block;
      float: none;
      .el-breadcrumb__inner {
        display: inline-flex;
        align-items: center;
        padding: 4px 8px;
        border-radius: 4px;
        transition: all 0.3s ease;
        cursor: pointer;

        &.is-link {
          color: var(--el-header-text-color);
          &:hover {
            color: var(--el-color-primary);
            background-color: var(--el-color-primary-light-9);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
          }
          &:active {
            transform: translateY(0);
          }
        }
        &.is-disabled {
          color: var(--el-text-color-disabled);
          cursor: not-allowed;
          &:hover {
            color: var(--el-text-color-disabled);
            background-color: transparent;
            transform: none;
            box-shadow: none;
          }
        }
        .breadcrumb-icon {
          margin-right: 6px;
          font-size: 14px;
          transition: transform 0.2s ease;
        }
        .breadcrumb-title {
          font-size: 14px;
          font-weight: 500;
          transition: color 0.3s ease;
        }

        &.is-link:hover .breadcrumb-icon {
          transform: scale(1.1);
        }
        &.is-disabled .breadcrumb-icon {
          opacity: 0.5;
        }
      }

      &:last-child .el-breadcrumb__inner {
        color: var(--el-header-text-color-regular);
        font-weight: 600;
        background-color: var(--el-color-info-light-8);
        cursor: default;

        &:hover {
          color: var(--el-header-text-color-regular);
          background-color: var(--el-color-info-light-8);
          transform: none;
          box-shadow: none;
        }
      }

      :deep(.el-breadcrumb__separator) {
        position: relative;
        margin: 0 8px;
        color: var(--el-text-color-secondary);
        transition: color 0.3s ease;
      }
    }
  }
}

.no-icon {
  .el-breadcrumb {
    .el-breadcrumb__item {
      .el-breadcrumb__inner {
        padding: 6px 10px;
      }
    }
  }
}

// 面包屑动画
.breadcrumb-enter-active,
.breadcrumb-leave-active {
  transition: all 0.4s ease;
}

.breadcrumb-enter-from {
  opacity: 0;
  transform: translateX(-20px) scale(0.9);
}

.breadcrumb-leave-to {
  opacity: 0;
  transform: translateX(20px) scale(0.9);
}

.breadcrumb-move {
  transition: transform 0.4s ease;
}

// 右键菜单样式
.context-menu-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1999;
}

.context-menu-wrapper {
  position: fixed;
  z-index: 2000;

  .context-menu {
    background: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color);
    border-radius: 6px;
    box-shadow: var(--el-box-shadow);
    padding: 4px 0;
    min-width: 160px;

    .menu-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 12px;
      cursor: pointer;
      transition: background-color 0.2s ease;
      font-size: 14px;
      color: var(--el-text-color-regular);

      &:hover {
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
      }

      .el-icon {
        font-size: 14px;
      }
    }

    .menu-divider {
      height: 1px;
      background-color: var(--el-border-color-lighter);
      margin: 4px 0;
    }
  }
}
</style>
